package com.practice.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.practice.reggie.common.CustomException;
import com.practice.reggie.common.R;
import com.practice.reggie.dto.DishDTO;
import com.practice.reggie.entity.Category;
import com.practice.reggie.entity.Dish;
import com.practice.reggie.entity.DishFlavor;
import com.practice.reggie.service.CategoryService;
import com.practice.reggie.service.DishFlavorService;
import com.practice.reggie.service.DishService;
import com.practice.reggie.service.impl.serviceImpl.CategoryServiceImpl;
import com.practice.reggie.service.impl.serviceImpl.DishServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param
     */
    @PostMapping
    public R<String> addDishAndFlavor(@RequestBody DishDTO dishDTO) {
        dishFlavorService.addDishAndFlavor(dishDTO);

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDTO.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("新增菜品成功！");
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     * @return
     */
    @PutMapping
    public R<String> updateDishAndFlavor(@RequestBody DishDTO dishDTO) {
        dishFlavorService.updateDishAndFlavor(dishDTO);
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDTO.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("修改菜品成功！");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器
        Page<Dish> pageI = new Page<>();
        Page<DishDTO> dishDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //添加排序条件
        wrapper.orderByDesc(Dish::getUpdateTime);
        //执行查询
        dishService.page(pageI, wrapper);

//        对象copy
        BeanUtils.copyProperties(pageI, dishDtoPage, "records");
        List<Dish> records = pageI.getRecords();
        List<DishDTO> collect = records.stream().map((item) -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(item, dishDTO);
            Long categoryId = item.getCategoryId();//菜品套餐id
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDTO.setCategoryName(categoryName);
            return dishDTO;
        }).collect(Collectors.toList());
        Page<DishDTO> dishDTOPage = dishDtoPage.setRecords(collect);

        return R.success(dishDTOPage);
    }

    /**
     * 修改反显信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDTO> delete(@PathVariable Long id) {
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        //执行查询
        Dish dish = dishService.getById(id);
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish, dishDTO);
        dishDTO.setFlavors(list);
        return R.success(dishDTO);
    }

    /**
     * 批量禁售起售
     *
     * @param type
     * @param ids
     * @return
     */
    @PostMapping("/status/{type}")
    public R<String> delete(@PathVariable int type, String[] ids) {
        log.info("flag:" + type + " ids:" + ids);
        if (ids == null || ids.length == 0) {
            throw new CustomException("参数有误");
        }
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Dish::getStatus, type).in(Dish::getId, ids);
        dishService.update(wrapper);
        String flag = type == 0 ? "已禁售" : "已启售";
        //执行查询
        return R.success(flag);
    }

    /**
     * 删除菜品(包括批量操作)------------------
     */
    @DeleteMapping
    public R<String> delete(String[] ids) {
        log.info("ids:" + ids);
        if (ids == null || ids.length == 0) {
            throw new CustomException("参数有误");
        }
        List<Dish> dishes = dishService.listByIds(Arrays.asList(ids));
        for (Dish dish : dishes) {
            if (dish.getStatus() == 1) {
                throw new CustomException("商品为起售状态无法删除！");
            }
        }
        dishService.del(ids);
        //执行查询
        return R.success("删除成功！");
    }

    /**
     * 套餐选择菜品
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDTO>> list(Dish dish) {
        List<DishDTO> dishDTOS = null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis获取数据
        dishDTOS = (List<DishDTO>) redisTemplate.opsForValue().get(key);
        if (dishDTOS != null) {
            R.success(dishDTOS);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Dish> eq = queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDTO> dishDtoList = list.stream().map((item) -> {
            DishDTO dishDto = new DishDTO();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        //放入redis缓存中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }

}
